package com.z.dao;

import java.util.List;

import com.db4o.ObjectContainer;
import com.db4o.query.Predicate;
import com.z.base.DbBase;
import com.z.entity.Account;

public class AccountDao extends DbBase {
	private static AccountDao accountDao;

	public static AccountDao getInstace() {
		if (accountDao == null) {
			accountDao = new AccountDao();
		}
		return accountDao;
	}

	@SuppressWarnings("serial")
	public Account findByPassword(final String account, final String password) {
		ObjectContainer db = null;
		List<Account> all = null;
		try {
			db = getDB();
			all = db.query(new Predicate<Account>() {
				@Override
				public boolean match(Account a) {
					return a.getAccount().equals(account)
							&& a.getPassword().equals(password);
				}
			});
		} catch (Exception e) {
		}
		if (all.size() > 0) {
			return all.get(0);
		}
		return null;
	}

	/**
	 * 检查是否存在管理员帐户
	 * 
	 * @return 0：尚未使用； 1：已经使用； -1：错误。
	 */
	@SuppressWarnings("serial")
	public int checkManagerExisted() {
		ObjectContainer db = null;
		List<Account> all = null;
		try {
			db = getDB();
			all = db.query(new Predicate<Account>() {
				@Override
				public boolean match(Account a) {
					if (a.isManager()) {
						return true;
					}
					return false;
				}
			});
			if (all != null && all.size() > 0) {
				return 1;
			}
			return 0;
		} catch (Exception e) {
			return -1;
		}
	}

	@SuppressWarnings("serial")
	public List<Account> findAccounts(final String account) {
		ObjectContainer db = null;
		List<Account> all = null;
		try {
			db = getDB();
			all = db.query(new Predicate<Account>() {
				@Override
				public boolean match(Account a) {
					if (a.getAccount().equals(account)) {
						return true;
					}
					return false;
				}
			});
		} catch (Exception e) {
			return null;
		}
		return all;
	}

	@SuppressWarnings("serial")
	public String findAccountName(final String id) {
		ObjectContainer db = getDB();
		List<Account> all = db.query(new Predicate<Account>() {
			@Override
			public boolean match(Account a) {
				if (a.getId().equals(id)) {
					return true;
				}
				return false;
			}
		});
		if(all!=null&&all.size()>0){
			return all.get(0).getName();
		}
		return null;
	}
}
